package activemq;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author lishaojun
 * @create 2019-07-08-下午 5:31
 */
public class JmsConsumer {
    public static final String ACTIVEMQ_URL = "tcp://106.13.85.181:61616"; //默认协议  AUTO+nio这种模式可以将原来的bio改成nio模式
    //public static final String ACTIVEMQ_URL = "nio://106.13.85.181:61618";
    public static final String QUEUE_NAME = "queue01";
    public static void main(String args[]) throws Exception{
        System.out.println("我是1号消费者");
        //1.创建连接工厂,按照地址给定的用户名密码
        ActiveMQConnectionFactory activeMQConnectionFactory=new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工厂获得连接
        Connection connection=activeMQConnectionFactory.createConnection();
        connection.start();
        //3.创建会话,方法两个参数一个是事务，一个是签收
        Session session=connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4.创建目的地，具体是队列或者是主题
        Queue queue=session.createQueue(QUEUE_NAME);
        //5.创建消息的消费者
        MessageConsumer messageConsumer=session.createConsumer(queue);
        /*
        方式1同步阻塞式receive()
        while (true){
           //TextMessage textMessage= (TextMessage) messageConsumer.receive();
            TextMessage textMessage= (TextMessage) messageConsumer.receive(4000);//消费者等4秒种，没有就自动断开
           if(textMessage!=null){
               System.out.println(textMessage.getText());
           }else{
               break;
           }
        }

        //6.关闭资源
        messageConsumer.close();
        session.close();
        connection.close();
        System.out.println("消息接收完毕");*/
        //接收方式2 使用监听器
        messageConsumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {

                if (null!=message&& message instanceof TextMessage){
                    TextMessage textMessage= (TextMessage) message;

                    try {
                        System.out.println(textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
                if (null!=message&& message instanceof MapMessage){
                    MapMessage mapMessage= (MapMessage) message;

                    try {
                        mapMessage.getStringProperty("c01");
                        System.out.println(mapMessage.getString("k1"));
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        System.in.read();//不写这句话，会出现消费者还没消费，资源就被关闭了
        messageConsumer.close();
        session.close();
        connection.close();
        System.out.println("消息接收完毕");
    }
}
